//
//  AuctionDetailVC.swift
//  LeGou
//
//  Created by lxm on 2022/10/15.
//

import UIKit

class AuctionDetailVC: ZMViewController {

    //MARK:--------------------属性--------------------
    var id : Int = 0
    
    var data = ZMUtil.fastNilBehavior(type: AuctionModels.AuctionDetail.self)
    
    var records = ZMUtil.fastNilBehavior(type: [AuctionModels.BidRecord].self)
    
    var payHelper = PayHelper()

    let timer = Observable<Int>.timer(.seconds(0), period: .seconds(1), scheduler: MainScheduler.instance)
    
    var currentVersion = 0

    //MARK:--------------------UI控件--------------------
    @IBOutlet weak var scyj: UILabel!
    
    @IBOutlet weak var countView: AuctionCountView!
    
    @IBOutlet weak var avatarsView: AuctionAvatarsView!
    
    let nav = NavigationBarView()
    
    @IBOutlet weak var banner: SDCycleScrollView!
    
    @IBOutlet weak var state: UILabel!
    // 价格前面的label
    @IBOutlet weak var pricePreTitle: UILabel!
    
    @IBOutlet weak var price: UILabel!
    
    @IBOutlet weak var startTimeLabel: UILabel!
    // 商品名字
    @IBOutlet weak var goodsName: UILabel!
    // 参与人数
    @IBOutlet weak var join: UILabel!
    // 围观人数
    @IBOutlet weak var look: UILabel!
    // 已出价
    @IBOutlet weak var givePrice: UILabel!
    // 起拍价
    @IBOutlet weak var startPrice: UILabel!
    // 加价幅度
    @IBOutlet weak var addRatio: UILabel!
    // 保证金
    @IBOutlet weak var insurance: UILabel!
    // 竞拍时间
    @IBOutlet weak var jpTime: UILabel!
    
    @IBOutlet weak var content: UIView!
    
    @IBOutlet weak var detialH: NSLayoutConstraint!
    
    @IBOutlet weak var recrodContent: UIStackView!
    
    @IBOutlet weak var recordContainer: UIView!
    
    @IBOutlet weak var sureButton: UIButton!
    
    @IBOutlet weak var recordCount: UILabel!
    
    @IBOutlet weak var redBagView: UIView!
    
    @IBOutlet weak var redBagTopTitle: UILabel!
    
    @IBOutlet weak var redBagMoneyTitle: UILabel!
    
    @IBOutlet weak var redBagSubTitle: UILabel!
    
    @IBOutlet weak var kefu: UIImageView!
    
    let loading = XMLoadingView()
    
    let web = WKWebView()
    //MARK:--------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        loading.showInView(fatherView: view)
        getInfo()
        getBidRecord()
    }
    
    //MARK:--------------------UI--------------------
    func setUI() {
        title = ""
        countView.endTime = Date().addingTimeInterval(36000)
        scyj.zm.setStrikethroughTitle(title: "市场原价：￥109")
        hbd_barHidden = true
        view.addSubview(nav)
        nav.backButton.setImage(UIImage.init(named: "auciton_back"), for: .normal)
        nav.autoBack = true
        // web
        content.addSubview(web)
        web.scrollView.isScrollEnabled = false
        web.scrollView.rx.observe(CGSize.self, "contentSize").subscribe(onNext:{ [unowned self] resp in
            if let size = resp {
                let h = size.height
                if self.web.superview != nil {
                   self.detialH.constant = h
                }
            }
        }).disposed(by: disposeBag)
        web.frame = CGRect(x: 12, y: 12, width: SCREEN_W - 24, height: 10)
        web.layer.cornerRadius = 8
        web.layer.masksToBounds = true
    }
    
    func addConstraints() {
        nav.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
        }
        
        web.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            
        }
    }
    
    //MARK:--------------------methods--------------------
    func bindAction() {
        data.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {return}
            if let imgs = resp.productInfo.sliderImage.zm.toArray() {
                self.banner.imageURLStringsGroup = imgs
            }
            self.state.text = resp.state.desForDetail().0
            self.state.textColor = resp.state.desForDetail().1
            self.scyj.zm.setStrikethroughTitle(title: "市场价 ￥\(resp.goodsRecord.markPrice.zm.toString(keep: 2))")
            self.price.text = resp.getcurrentMoney.zm.toString(keep: 2)
            self.goodsName.text = resp.productInfo.storeName
            
            self.join.isHidden = resp.beatNum == 0
            self.join.text = "参与\(resp.beatNum)次"
            self.look.text = "围观\(resp.currentViewer)"
            self.givePrice.text = "已出价\(resp.offerNum)人"
            //TODO: 头像
//            self.avatarsView.avatars = []
            
            self.startPrice.text = "¥" + resp.goodsRecord.startPrice.zm.toString(keep: 2)
            self.addRatio.text = "¥" + resp.goodsRecord.stepPrice.zm.toString(keep: 2)
            self.insurance.text = "¥" + resp.bail.zm.toString(keep: 2)
            self.jpTime.text = "\(resp.goodsRecord.startTime.zm.stringToString(toFormate: "MM.dd HH:mm:ss"))-\(resp.goodsRecord.endTime.zm.stringToString(toFormate: "MM.dd HH:mm:ss"))"
            self.web.loadHTMLString(resp.productInfo.content.zm.htmlBigSizeString(), baseURL: nil)
            
            self.sureButton.backgroundColor = Style.mainColor
            self.sureButton.setTitleColor(.white, for: .normal)
            self.sureButton.setImage(UIImage.init(named: "auction_d_hammer"), for: .normal)
            self.sureButton.isEnabled = true
            
            self.redBagSubTitle.isHidden = true
            
            switch resp.state {
                case .wait:
                    self.redBagView.isHidden = true
                    self.pricePreTitle.text = "起购价¥"
                
                    if let start = resp.goodsRecord.startTime.zm.toDate(formate: "yyyy-MM-dd HH:mm:ss"),
                       start.timeIntervalSince1970 - RedBagService.shared.nowTimeinterval < 3600
                    {
                        // 距离开始不足一小时
                        self.countView.isHidden = false
                        self.countView.endTime = start
                        self.startTimeLabel.text = "距离开始仅剩"
                    } else {
                        self.startTimeLabel.text = "\(resp.goodsRecord.startTime.zm.stringToString(toFormate: "HH.mm"))-\(resp.goodsRecord.endTime.zm.stringToString(toFormate: "HH.mm"))进行"
                        self.countView.isHidden = true
                    }
                    if NotificationTool.shard.checkNotificationExist(AuctionService.shared.generateNotificationIdstr(self.id, resp.goodsRecord.activityId)) {
                        self.sureButton.setImage(UIImage.init(named: "auction_clock_g"), for: .normal)
                        self.sureButton.setTitle("取消提醒", for: .normal)
                        self.sureButton.backgroundColor = UIColor.zm.color(hexString: "#48A1A7", 0.1)
                        self.sureButton.setTitleColor("#48A1A7".zm.hex(), for: .normal)
                    } else {
                        self.sureButton.setImage(UIImage.init(named: "auction_clock_w"), for: .normal)
                        self.sureButton.setTitle("提醒我", for: .normal)
                        self.sureButton.backgroundColor = "#48A1A7".zm.hex()
                        self.sureButton.setTitleColor(.white, for: .normal)
                    }
                case .process:
                    self.redBagView.isHidden = false
                    self.redBagTopTitle.text = "预估赚"
                    self.redBagMoneyTitle.text = "¥\(resp.rewardMoney.zm.xmToString(keep: 2))"
                    self.pricePreTitle.text = "当前价¥"
                    self.startTimeLabel.text = "距离结束仅剩"
                    self.countView.isHidden = false
                    if let date = resp.goodsRecord.endTime.zm.toDate(formate: "yyyy-MM-dd HH:mm:ss") {
                        self.countView.endTime = date
                    }
                    // 用户竞购状态：0未出价 1已出价且出局 2已出价且领先 3竞拍成功未中 4竞拍成功已中
                    if resp.ahState == 0 {
                        // 0未出价
                        self.sureButton.setTitle("我要竞购 赚￥\(resp.joinShare.zm.xmToString(keep: 2))", for: .normal)
                    } else if resp.ahState == 1 {
                        // 1已出价且出局
                        self.sureButton.setTitle("再次出价 赚￥\(resp.joinShare.zm.xmToString(keep: 2))", for: .normal)
                    } else if resp.ahState == 2 {
                        // 2已出价且领先
                        self.sureButton.setTitle("已出价 ￥\(resp.currentPrice.zm.xmToString(keep: 2))", for: .normal)
                        self.sureButton.backgroundColor = "#CCCCCC".zm.hex()
                        self.sureButton.isEnabled = false
                    }
                case .success:
                    self.redBagView.isHidden = resp.beatNum == 0
                    self.redBagTopTitle.text = "共赚"
                    self.redBagMoneyTitle.text = "¥\(resp.rewardMoney.zm.xmToString(keep: 2))"
                
                    self.pricePreTitle.text = "竞购价¥"
                    self.countView.isHidden = true
                    self.startTimeLabel.text = "竞购\(resp.goodsRecord.endTime.zm.stringToString(toFormate: "HH:mm"))已结束"
                    if resp.ahState == 3 {
                        // 3竞拍成功未中
                        self.sureButton.setTitle("本期竞购已结束", for: .normal)
                        self.sureButton.isEnabled = false
                        self.sureButton.backgroundColor = "#CCCCCC".zm.hex()
                    } else if resp.ahState == 4 {
                        // 4竞拍成功已中
                        if resp.finalPaid == 1 {
                            self.sureButton.backgroundColor = "#CCCCCC".zm.hex()
                            self.sureButton.setTitle("本期竞购已结束", for: .normal)
                        } else {
                            self.sureButton.setTitle("去付尾款 ￥\(resp.surplusPrice.zm.toString(keep: 2))", for: .normal)
                        }
                    } else {
                        self.sureButton.setTitle("本期竞购已结束", for: .normal)
                        self.sureButton.isEnabled = false
                        self.sureButton.backgroundColor = "#CCCCCC".zm.hex()
                    }
                case .toNext:
                    self.redBagView.isHidden = true
                    self.pricePreTitle.text = "流拍价¥"
                    self.countView.isHidden = true
                    self.startTimeLabel.text = "竞购\(resp.goodsRecord.endTime)已结束"
                    self.sureButton.setTitle("本期竞购已流拍", for: .normal)
                    self.sureButton.backgroundColor = "#CCCCCC".zm.hex()
                    self.sureButton.isEnabled = false
                default : break
            }
        }).disposed(by: disposeBag)
        
        // 记录
        records.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {return}
            self.avatarsView.avatars = resp.map({$0.avatar})
            self.recrodContent.arrangedSubviews.forEach {[unowned self]  v in
                self.recrodContent.removeArrangedSubview(v)
            }
            for i in 0 ..< resp.count {
                let m = resp[i]
                let color = i == 0 ? "#DE3F26".zm.hex() : "#CCCCCC".zm.hex()
                let rv = AuctionDetailRecordView()
                rv.leftLabel.setTitle("\(m.showId)  \(m.bidStateStr) \(m.cityName) \(m.createTime.zm.stringToString(toFormate: "MM.dd HH:mm:ss"))", for: .normal)
                rv.leftLabel.setTitleColor(color, for: .normal)
                rv.leftLabel.tintColor = color
                rv.rightLabel.text = "¥\(m.stepAmount.zm.toString(keep: 2))"
                rv.rightLabel.textColor = color
                self.recrodContent.addArrangedSubview(rv)
            }
            self.recordContainer.isHidden = resp.count == 0
        }).disposed(by: disposeBag)
        
        payHelper.paySuccess = { [weak self] in
            guard let self = self else {return}
            ZMToast.showToast(title: "充值成功")
            self.refreshChangeData()
        }
        
        timer.subscribe(onNext:{ [unowned self] resp in
            self.checkVersion()
        }).disposed(by: disposeBag)
        
        _ = kefu.zm.addTapGestureRecognizer(target: self, action: #selector(onKefu))
        
        _ = recordCount.zm.addTapGestureRecognizer(target: self, action: #selector(onRecord))
        
        ZMNotification.shard.subject.subscribe(onNext:{ [unowned self] resp in
            switch resp {
                case .auctionRefersh:
                    self.refreshChangeData()
                default:break
            }
        }).disposed(by: disposeBag)
        
        countView.onCountOver = { [weak self] in
            guard let self = self, let info = self.data.value, (info.state == .wait || info.state == .process) else {return}
            if developMode != 1 {
                ZMToast.showToast(title: "发现数据不一致，主动更新")
            }
            self.refreshChangeData()
        }
    }
    
    @objc func onKefu() {
        CommonService.shared.showContactService()
    }
    
    @objc func onRecord() {
        let vc = BidRecords()
        vc.ahGoodsRecordId = id
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    
    // 检查版本号
    func checkVersion() {
        guard let resp = data.value, resp.state != .success, resp.state != .toNext, resp.state != .soldOut else {return}
        AuctionAPI.checkVersion(id).rxRequest(type: Int.self).subscribe(onNext:{ [unowned self] resp in
            if self.currentVersion != resp {
                self.refreshChangeData()
                self.getBidRecord()
            }
            self.currentVersion = resp
        }).disposed(by: disposeBag)
    }
    
    // 获取改动数据
    func refreshChangeData() {
//        m.des
        XMLogger.info("发现数据不一致，需要更新")
        let begin = Date()
        AuctionAPI.changeData(id).rxRequest(type: AuctionModels.AuctionDetail.self).subscribe(onNext:{ [unowned self] resp in
            guard let m = self.data.value else {return}
            if m.ahState <= 2, resp.ahState > 2, let challenge = resp.challengerDataResponse {
                // 出结果了，去获取结果
                self.showResult(r: challenge)
            }
            self.copyToDetial(source: resp, target: m)
            self.data.update()
            XMLogger.info("变化数据请求耗时：\(Date().timeIntervalSince1970 - begin.timeIntervalSince1970)S")
        }).disposed(by: disposeBag)
    }
    
    func copyToDetial(source : AuctionModels.AuctionDetail, target : AuctionModels.AuctionDetail) {
        target.ahState = source.ahState
        target.bail = source.bail
        target.beatNum = source.beatNum
        target.currentPrice = source.currentPrice
        target.currentViewer = source.currentViewer
        target.finalPaid = source.finalPaid
        target.joinShare = source.joinShare
        target.offerNum = source.offerNum
        target.orderId = source.orderId
        target.rewardMoney = source.rewardMoney
        target.state = source.state
        target.surplusPrice = source.surplusPrice
        target.challengerDataResponse = source.challengerDataResponse
    }
    
    // 显示结果
    func showResult(r : AuctionModels.ChallengerDataResponse) {
        let v = ZMUtil.loadNibViewFullScreen(nibName: AuctionRewardView.self)
        v.avatar.zm.setImage(urlStr: r.avatar)
        v.name.text = r.nickname
        v.totalPrice.setTitle("出价¥\(r.currentPrice.zm.toString(keep: 2))", for: .normal)
        v.activityNum.setTitle("+\(r.gainActivity.zm.toString(keep: 4))活跃度", for: .normal)
        v.allReward.text = "您共赚¥\(r.rewardMoney.zm.toString(keep: 2))元"
        if r.challengerState == 1 {
            v.sureBtn.setTitle("去付尾款（¥\(r.surplusPrice.zm.toString(keep: 2))）", for: .normal)
        } else {
            v.sureBtn.setTitle("确定", for: .normal)
        }
        
        v.sureBtn.rx.tap.subscribe(onNext:{ [unowned self, weak v] resp in
            guard let v = v else {return}
            if r.challengerState == 1 {
                let vc = AuctionCreateOrderVC()
                vc.recordId = id
                self.navigationController?.pushViewController(vc, animated: true)
            }
            v.removeFromSuperview()
        }).disposed(by: v.disposeBag)
        
        APPWindow?.addSubview(v)
    }
    
    func getBidRecord() {
        AuctionAPI.auctionGetRecord(["limit" : 3, "page" : 1, "recordId" : id]).rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
            let total = JSON(resp)["total"].intValue
            if let list = resp["list"] as? [[String : Any]], let m = [AuctionModels.BidRecord].deserialize(from: list) {
                self.records.accept(m.compactMap({$0}))
            }
            self.recordCount.text = "\(total)条"
        }).disposed(by: disposeBag)

    }
    
    func getInfo() {
        ZMAPIManage<AuctionModels.AuctionDetail>.rxSendRequest(AuctionAPI.auctionDetail(id)).subscribe(onNext:{ [unowned self] resp in
            if resp.code == .success, let data = resp.data {
                self.data.accept(data)
                self.loading.hideView(anmation: true)
            } else if resp.code == .auctionFreshMan {
                // 新手
                self.navigationController?.popViewController(animated: true)
            } else {
                self.loading.showError(resp.message)
            }
        }, onError: { e in
            self.loading.showError(e.localizedDescription)
        }).disposed(by: disposeBag)
    }
    
    @IBAction func onPay(_ sender: Any) {
        guard let resp = data.value else {return}
        if resp.state == .wait {
            // 提醒
            let idStr = AuctionService.shared.generateNotificationIdstr(id, resp.goodsRecord.activityId)

            if NotificationTool.shard.checkNotificationExist(idStr) {
                // 存在->取消提醒
                NotificationTool.shard.cancelNotification(idStr)
            } else {
                // 不存在->提醒
                guard let startDate = resp.goodsRecord.startTime.zm.toDate(formate: "yyyy-MM-dd HH:mm:ss") else {return}
                let adDate = startDate - (60 * 3)
                let diff = adDate.timeIntervalSince1970 - RedBagService.shared.nowTimeinterval
                if diff <= 0 {
                    ZMToast.showToast(title: "距离开始时间不足3分钟")
                    return
                }
                NotificationTool.shard.addNotifaction(identifier: idStr, timeInterval: diff, title: "乐购竞购提醒", subtitle: "有一场竞购即将开始", body: "有一场 \(startDate.zm.toString("HH:mm")) 的竞购活动即将开始")
                ZMToast.showToast(title: "预约成功，将在开抢前3分钟提醒")
            }
            NotificationTool.shard.getNotification({ [weak self] in
                guard let self = self else {return}
                DispatchQueue.main.async {
                    self.data.update()
                }
            })
        } else if resp.state == .success {
            if resp.finalPaid == 0 {
                // 成功 & 未支付
                let vc = AuctionCreateOrderVC()
                vc.recordId = id
                navigationController?.pushViewController(vc, animated: true)
            }
        } else {
            auction()
        }
    }
    
    func setStateStr() {
        
    }
    
    //竞购
    func auction() {
        let typeStr = "AUCTION"
        let id = "10"
        ZMToast.showActivity()
        MineAPI.create_auth_code(["id" : id,"userId":ZMAppShareData.share.safeUserId, "type":typeStr]).rxRequest(type: String.self).flatMapLatest { r ->  Observable<[String : Any]> in
            // 生成本地将军令
            let code = AppHelper.generalOrder(userId: "\(ZMAppShareData.share.safeUserId)",
                                              randomKey: ZMAppShareData.share.loginInfo!.token,
                                              showId: ZMAppShareData.share.safeUserInfo.showId,
                                              time: Int(r) ?? 0,
                                              type: typeStr, id: id)
            let pa = [
                "code" : code,
                "encryptedContent" : self.encryptParams(),
                "userId" : ZMAppShareData.share.safeUserId,
            ] as [String : Any]
            return AuctionAPI.auction(pa).rxRequest(type: [String : Any].self)
        }.subscribe(onNext:{ [unowned self] resp in
            ZMToast.hiddenActivity()
            let json = JSON(resp)
            // 成功
            if json["state"].int == 0 {
                // 成功
                self.refreshChangeData()
            } else if json["balanceState"].boolValue  {
                // 保证金不足, 弹框支付
                let v = ZMUtil.loadNibViewFullScreen(nibName: AuctionResiduePay.self)
                APPWindow?.addSubview(v)
                let price = json["difference"].doubleValue.zm.toString(keep: 2)
                v.money.text = price
                v.needLabel.text = "参与本期竞购，创客钱包可用余额需>¥\(json["bail"].doubleValue.zm.toString(keep: 2))元"
                v.currentLabel.text = "当前创客钱包 (¥ \(json["mallMoney"].doubleValue.zm.toString(keep: 2)))"
                v.onPayCallback = { type in
                    self.recharge(money: price, type: type, v : v)
                }
            } else {
                // 失败
//                ZMToast.showToast(title: "支付失败")
//                ZMToast.showToast(title: )
            }
        }, onError: { e in
//            close(false)
        }).disposed(by: self.disposeBag)
    }
    
    // 充值
    func recharge(money : String, type : EnumPayTool, v : UIView) {
        ZMToast.showActivity()
        AuctionAPI.balanceRecharge(["amount" : money]).rxRequest(type: [String : String].self).subscribe(onNext:{ [unowned self] resp in
            ZMToast.hiddenActivity()
            self.payHelper.sendPay(currentVC: self, orderNo:JSON(resp)["orderNo"].stringValue , payType: type) { ok in
                if ok {
                    v.removeFromSuperview()
                }
            }
        }).disposed(by: disposeBag)
    }
    
    func updateStartLabel() {
//        guard let resp = data.value,
//              let start = resp.goodsRecord.startTime.zm.toDate(formate: "yyyy-MM-dd HH:mm:ss"),
//              let end = resp.goodsRecord.endTime.zm.toDate(formate: "yyyy-MM-dd HH:mm:ss")
//        else {
//            return
//        }
//        if resp.state == .wait {
//            let diff = start.timeIntervalSince1970 - RedBagService.shared.nowTimeinterval
//            if diff <= 3600 && diff >= 0 {
//                // 小于一个小时倒计时
//                let count = AppHelper.countTime(now: RedBagService.shared.nowTimeinterval, end: start.timeIntervalSince1970)
//                self.startTimeLabel.text = "距开始仅剩 \(String(format: "%02d", count.h)):\(String(format: "%02d", count.m)):\(String(format: "%02d", count.s))"
//            } else {
//                self.startTimeLabel.text = "\(resp.goodsRecord.startTime.zm.stringToString(toFormate: "HH.mm"))-\(resp.goodsRecord.endTime.zm.stringToString(toFormate: "HH.mm"))进行"
//            }
//        } else if resp.state == .process {
//            let endTimeInterval = end.timeIntervalSince1970
//            let count = AppHelper.countTime(now: RedBagService.shared.nowTimeinterval, end: endTimeInterval)
//            self.tipsLabel.text = "距竞购结束仅剩 \(String(format: "%02d", count.h)):\(String(format: "%02d", count.m)):\(String(format: "%02d", count.s))"
//        } else {
//            self.tipsLabel.text = "竞购 \(start.zm.toString("HH:mm")) 已结束"
//        }
    }
    
    func encryptParams() -> String {
        let pa = "{recordId : \(id)}"
        let after = ZMOcHelper.encrypt(pa, key: theKey)
        return after
    }
    
    deinit {
        XMLogger.info("detail deinit")
    }
}


struct PwdInputInfo {
    var title : String = "请输入交易密码"
    var money : String
    var left : String
    var right : String
//    var unitHide = false
    // 0 普通支付, 1 积分支付
    var type = 0
}

class PayHelper : NSObject, PayCheckerDelegate {
    var disposeBag = DisposeBag()
    
    var paychecker : PayChecker<String> = PayChecker()
    // 0 微信 1 支付宝
    var payType : EnumPayTool = .wechat
    
    var paySuccess : (()->())?
    
    override init() {
        super.init()
        paychecker.delegate = self
        paychecker.timeOutTimes = 30
    }
    

    
    func sendPay(currentVC : ZMViewController, orderNo : String, payType : EnumPayTool, info : PwdInputInfo? = nil, otherInfo : [String : Any]? = nil, complete:@escaping (_ ok : Bool)->()) {
        // 校验支付密码
        
        
        
        self.payType = payType
        let payTypeStr = VIPMallService.shared.getPayStr(type: payType)

        var pa = ["orderNo" : orderNo, "payType" : payTypeStr] as [String : Any]
        
        if let otherInfo = otherInfo {
            for (k, v) in otherInfo {
                pa[k] = v
            }
        }
        
        if payType == .balancePay || payType == .ckPay || payType == .integral {
            guard let info = info else {
                ZMToast.showToast(title: "支付信息出错")
                return
            }
            
            if !ZMAppShareData.share.safeUserInfo.isTradeOk {
                // 判断是否设置交易密码
                ZMAlertView.show(content: "还未设置交易密码", left: "关闭", right: "马上去设置") {
                    
                } onRight: {
                    let cls = Swift.type(of: currentVC)
                    MineService.shared.tradeSuccessToVC = cls
                    let vc = TradeFroget()
                    currentVC.navigationController?.pushViewController(vc, animated: true)
                    complete(true)
                }
                return
            }
            
            
            CommonService.shared.showPsdInput(title : info.title, money: info.money, left : info.left, right : info.right, type: info.type) { psd, close in
                pa["tradePwd"] = psd
                VIPMallAPI.payInfo(pa).rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
                    complete(true)
                    // 支付成功
                    if let paySuccess = self.paySuccess {
                        paySuccess()
                    }
                    close(true)
                }, onError: { _ in
                    complete(false)
                    close(false)
                }).disposed(by: self.disposeBag)
            }
        } else {
            VIPMallAPI.payInfo(pa).rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
                let payStr = JSON(resp)["alipayRequest"].stringValue
                if payTypeStr == "weixin" {
                    ZMPayManager.shard.wechatPay(resp, orderNum: orderNo)
                } else {
                    ZMPayManager.shard.aliPayWithInfo(payStr, orderNum: orderNo)
                }
                self.paychecker.checkData.accept(orderNo)
                complete(true)
            }, onError: { _ in
                complete(false)
            }).disposed(by: self.disposeBag)
        }
    }
    
    func check(_ keepOn: @escaping (() -> ())) {
        guard let currentPayInfo = paychecker.checkData.value else {return}
        XMLogger.tracking("开始检测支付--\(paychecker.checkTimes)---\(currentPayInfo)")
        let api = payType == .wechat ? VIPMallAPI.wxCheck(currentPayInfo) : VIPMallAPI.alipayCheck(currentPayInfo)
        api.rxRequest(type: Bool.self).subscribe(onNext:{ [weak self] resp in
            guard let self = self else {return}
            if resp {
                // 支付成功
                if let paySuccess = self.paySuccess {
                    paySuccess()
                }
                self.paychecker.checkData.accept(nil)
                XMLogger.tracking("检测成功")
            } else {
                if let v = self.paychecker.checkData.value, v == currentPayInfo {
                    XMLogger.tracking("检测失败---调用keepOn")
                    keepOn()
                }
            }
        }, onError: { _ in
            if let v = self.paychecker.checkData.value, v == currentPayInfo {
                XMLogger.tracking("检测失败---调用keepOn")
                keepOn()
            }
        }).disposed(by: disposeBag)
    }
}
